﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Chowpoo.Common;
using Chowpoo.Util;
using CourseSystem.Common;
using CourseSystem.Common.Chat;
using CourseSystem.Common.Helpers;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Entities;
using CourseSystem.Core.Enum;
using CourseSystem.Stat;
using CourseSystem.Stat.ActionFilter;
using Webdiyer.WebControls.Mvc;


namespace CourseSystem.Web.Controllers
{
    [UserAuth(UserType = UserTypeEnum.Student)]
    public class InteractionController : BaseController
    {
        //
        // GET: /Interaction/

        public ActionResult Index(int? type)
        {
            type = type.CheckInt(0);

            switch (type)
            {
                case 0: return RedirectToAction("Question", new { isCommon = 0 }); break;
                case 1: return RedirectToAction("Question", new { isCommon = 1 }); break;
                case 2: return RedirectToAction("Forums", new { isDigest = 0 }); break;
                case 3: return RedirectToAction("Forums", new { isDigest = 1 }); break;
            }
            return NotFound();
        }

        [StatFilter]
        [UrlStatFilter]
        public ActionResult Forums(int isDigest)
        {
            SetForums(isDigest);
            ViewData["isDigest"] = isDigest;
            return View();
        }

        public ActionResult Chat()
        {
            ChatHelper.AddOnline();
            return View();
        }

        public ActionResult ChatButtom()
        {
            return PartialView();
        }

        public ActionResult ChatMessage()
        {
            ViewData.Model = ChatHelper.ChatList;
            return PartialView();
        }

        public ActionResult ChatOnline()
        {
            ChatHelper.AddOnline();
            ViewData.Model = ChatHelper.OnlineChatDic;
            return PartialView();
        }

        private void SetForums(int isDigest)
        {
            if (isDigest != 0 && isDigest != 1)
                isDigest = 0;
            if (isDigest == 0)
                ViewData["type"] = 2;
            else ViewData["type"] = 3;
            ViewData["isDigest"] = isDigest;
        }

        [UploadAuth]
        [UserAuth(UserType = UserTypeEnum.Student, IsNotExpert = true)]
        public ActionResult Posts(int? id, int? fid, int? tid, int? isDigest)
        {
            ViewData["isDigest"] = isDigest;
            id = id.CheckInt(0);
            fid = fid.CheckInt(0);
            tid = tid.CheckInt(0);
            if (id != 0)
            {
                var info = PostsBLL.Get(id.Value);
                if (info == null || !InterActionHelper.IsHasPower(info))
                    return NotFound();
                return View(info);
            }
            if (fid == 0)
                return NotFound();

            var forumsInfo = ForumsBLL.Get(fid.Value);
            if (forumsInfo == null)
                return NotFound();
            //判断是否能回复
            if (tid != 0)
            {
                var lastPostInfo = PostsBLL.GetList(tid.Value).OrderByDescending(o => o.Id).FirstOrDefault();
                if (lastPostInfo == null)
                    return NotFound();
                var isAuthor = lastPostInfo.TopicsInfo.PosterId == UserHelper.LoginUser.Id &&
                               lastPostInfo.TopicsInfo.PosterType == UserHelper.GetLoginUserType();
                if (isAuthor && lastPostInfo.PosterId == UserHelper.LoginUser.Id && lastPostInfo.PosterType == UserHelper.GetLoginUserType())
                {
                    SetAlertMsg("自己发布的帖子在别人还没回复时自己不能回复!", true);
                    return RedirectToAction("PostsView", new { id = id, isDigest });
                }
            }
            return View(new PostsInfo { Fid = fid.Value, Tid = tid.Value });
        }

        [UserAuth(UserType = UserTypeEnum.Student, IsNotExpert = true)]
        [HttpPost]
        [ValidateInput(false)]
        [UploadedAuth]
        public ActionResult Posts(PostsInfo info, int? isDigest)
        {
            ViewData["isDigest"] = isDigest;
            var ran = ViewData["ranStr"].ToString();
            ViewData.Model = info;
            if (!ModelState.IsValid)
                return View();
            if (info.Fid == 0)
            {
                return NotFound();
            }
            if (info.Id != 0)
            {
                var oldInfo = PostsBLL.Get(info.Id);
                if (oldInfo == null || !InterActionHelper.IsHasPower(oldInfo))
                    return NotFound();
                oldInfo.Title = info.Title;
                oldInfo.Message = info.Message;
                if (PostsBLL.Edit(oldInfo))
                {
                    ViewData.Model = oldInfo;
                    PostsAttachHelper.ClearUselessAttach(oldInfo.Message, ran, oldInfo.Id);
                    if (oldInfo.IsTopic)
                    {
                        oldInfo.TopicsInfo.Title = oldInfo.Title;
                        if (TopicsBLL.Edit(oldInfo.TopicsInfo))
                        {
                            SetAlertMsg("编辑成功.");
                            return View();
                        }
                        SetAlertMsg("未知错误.");
                        return View();
                    }
                    SetAlertMsg("编辑成功.");
                    return View();
                }
                SetAlertMsg("未知错误.");
                return View();
            }
            var addInfo = new PostsInfo
                              {
                                  Fid = info.Fid,
                                  Message = info.Message,
                                  Title = info.Title,
                                  PostTime = DateTime.Now,
                                  PosterType = UserHelper.GetLoginUserType(),
                                  PosterId = UserHelper.LoginUser.Id,
                                  PosterName = UserHelper.LoginUser.UserName,
                                  Tid = info.Tid
                              };
            ViewData.Model = addInfo;
            //新建主题
            if (info.Tid == 0)
            {
                var topicInfo = new TopicsInfo
                                    {
                                        Fid = info.Fid,
                                        IsDigest = false,
                                        PosterId = UserHelper.LoginUser.Id,
                                        PosterName = UserHelper.LoginUser.UserName,
                                        PosterType = UserHelper.GetLoginUserType(),
                                        PostTime = DateTime.Now,
                                        Title = info.Title,
                                        Status = 0

                                    };
                if (!TopicsBLL.Add(topicInfo))
                {
                    SetAlertMsg("未知错误.");
                    return View();
                }
                addInfo.Tid = topicInfo.Id;
                addInfo.IsTopic = true;
            }
            else
            {

                //判断是否能够回复
                var lastPostInfo = PostsBLL.GetList(info.Tid).OrderByDescending(o => o.Id).FirstOrDefault();
                if (lastPostInfo == null)
                    return NotFound();
                var isAuthor = lastPostInfo.TopicsInfo.PosterId == UserHelper.LoginUser.Id &&
                               lastPostInfo.TopicsInfo.PosterType == UserHelper.GetLoginUserType();
                if (isAuthor && lastPostInfo.PosterId == UserHelper.LoginUser.Id && lastPostInfo.PosterType == UserHelper.GetLoginUserType())
                {
                    SetAlertMsg("自己发布的帖子在别人还没回复时自己不能回复!", true);
                    return RedirectToAction("PostsView", new { id = info.Id, isDigest });
                }
            }
            if (PostsBLL.Add(addInfo))
            {
                ForumsHelper.EditLastUpdate(addInfo.Fid, addInfo.IsTopic);
                if (!addInfo.IsTopic)
                    TopicsHelper.EditLastUpdate(addInfo.Tid);
                PostsAttachHelper.ClearUselessAttach(addInfo.Message, ran, addInfo.Id);
                SetAlertMsg("发表成功.");
                return View();
            }
            SetAlertMsg("未知错误.");
            return View();
        }

        [UserAuth(UserType = UserTypeEnum.Teacher)]
        public ActionResult TopicsSetDigest(int id)
        {
            var info = TopicsBLL.Get(id);
            if (info == null)
                return NotFound();
            info.IsDigest = !info.IsDigest;
            if (TopicsBLL.Edit(info))
            {
                SetAlertMsg("设置成功.", true);
            }
            return RedirectToAction("PostsView", new { id });
        }

        [StatFilter]
        public ActionResult Topics(int id, int? isDigest)
        {
            SetForums(isDigest.CheckInt(0));
            var info = ForumsBLL.Get(id);
            if (info == null)
                return NotFound();
            return View(info);
        }

        public ActionResult TopicsListUc(int? pid, string search, int isDigest, int fid)
        {
            if (isDigest != 0 && isDigest != 1)
                return NotFound();
            CommonRequest.ClearCache();
            var list = TopicsBLL.GetList(fid, isDigest == 1 ? true : (bool?)null, search).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            ViewData["isDigest"] = isDigest;
            return PartialView(model);
        }

        public ActionResult PostsListUc(int? pid, int tid, int? isDigest)
        {
            ViewData["isDigest"] = isDigest;
            CommonRequest.ClearCache();
            var list = PostsBLL.GetList(tid).OrderBy(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        [UserAuth(UserType = UserTypeEnum.Teacher)]
        public ActionResult PostsDel(int id)
        {
            var info = PostsBLL.Get(id);
            if (info == null)
                return NotFound();
            if (PostsBLL.Del(info.Id))
            {

                SetAlertMsg("删除成功.", true);
                if (info.IsTopic)
                {
                    var toDelAttachPostIdList = PostsBLL.GetList(info.Tid).Select(o => o.Id).ToList();
                    PostsAttachBLL.DelFileByExpress(o => toDelAttachPostIdList.Contains(o.PostId));
                    TopicsBLL.Del(info.Tid);
                    return RedirectToAction("Topics", new { id = info.Fid });
                }
                else
                {
                    PostsAttachBLL.DelFileByExpress(o => o.PostId == id);
                    return RedirectToAction("PostsView", new { id = info.Tid });
                }
            }
            return RedirectToAction("Topics", new { id = info.Fid });
        }
        [StatFilter]
        public ActionResult PostsView(int id, int? isDigest)
        {
            SetForums(isDigest.CheckInt(0));
            ViewData["isDigest"] = isDigest.CheckInt(0);
            var info = TopicsBLL.Get(id);
            if (info == null)
                return NotFound();
            TopicsBLL.UpdateView(id);
            return View(info);
        }

        public ActionResult ForumsListUc(int? pid, string search, int isDigest)
        {
            CommonRequest.ClearCache();
            var list = ForumsBLL.GetList(search).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            ViewData["isDigest"] = isDigest;
            return PartialView(model);
        }
        [StatFilter]
        [UrlStatFilter]
        public ActionResult Question(int isCommon)
        {
            if (isCommon != 0 && isCommon != 1)
                return NotFound();
            ViewData["type"] = isCommon;
            ViewData["isCommon"] = isCommon;
            return View();
        }

        public ActionResult QuestionListUc(int? pid, string search, int isCommon, int? isAll)
        {
            isAll = isAll.CheckInt(0);
            CommonRequest.ClearCache();
            var list = QuestionBLL.GetList(search, null, isCommon == 1, isAll == 0 ? 0 : UserHelper.Student.Id).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        [UserAuth(IsLimt = true, UserType = UserTypeEnum.Student)]
        [UploadAuth]
        public ActionResult QuestionEdit(int? id)
        {
            if (id.HasValue && id != 0)
            {
                var info = QuestionBLL.Get(id.Value);
                if (info == null || info.StudentInfo == null)
                    return NotFound();
                if (UserHelper.LoginUser.UserType != UserTypeEnum.Student || UserHelper.LoginUser.Id != info.AskerId)
                    return NotFound();
                return View(info);
            }
            return View(new QuestionInfo { });
        }

        [HttpPost]
        [ValidateInput(false)]
        [UserAuth(IsLimt = true, UserType = UserTypeEnum.Student)]
        [UploadedAuth]
        public ActionResult QuestionEdit(QuestionInfo info)
        {
            var ran = ViewData["ranStr"].ToString();
            ViewData.Model = info;
            if (string.IsNullOrEmpty(info.QuestionContentInfo.DetailContent))
                ModelState.AddModelError("QuestionContentId", "必须填写");
            if (!ModelState.IsValid)
                return View();
            if (info.Id != 0)
            {
                var oldInfo = QuestionBLL.Get(info.Id);
                if (oldInfo == null || oldInfo.StudentInfo == null)
                    return NotFound();
                if (UserHelper.LoginUser.UserType != UserTypeEnum.Student || UserHelper.LoginUser.Id != oldInfo.AskerId)
                    return NotFound();
                oldInfo.QuestionContentInfo.DetailContent = info.QuestionContentInfo.DetailContent;
                if (CommonContentBLL.Edit(oldInfo.QuestionContentInfo) && QuestionBLL.Edit(oldInfo))
                {
                    AttachmentsHelper.ClearUselessAttach(oldInfo.QuestionContentInfo.DetailContent, ran, oldInfo.QuestionContentInfo.Id);
                    SetAlertMsg("编辑成功.");
                    return View(oldInfo);
                }
                SetAlertMsg("未知错误.");
                return View();
            }
            var addInfo = new QuestionInfo
                              {
                                  QuestionContentInfo = new CommonContentInfo { DetailContent = info.QuestionContentInfo.DetailContent },
                                  IsAnswered = false,
                                  Hits = 0,
                                  IsCommon = false,
                                  QuestionTime = DateTime.Now,
                                  AskerName = UserHelper.LoginUser.UserName,
                                  AskerId = UserHelper.LoginUser.Id,
                                  AnswerContentInfo = new CommonContentInfo { }
                              };
            if (QuestionBLL.Add(addInfo))
            {
                AttachmentsHelper.ClearUselessAttach(addInfo.QuestionContentInfo.DetailContent, ran, addInfo.QuestionContentInfo.Id);
                SetAlertMsg("提问成功.");
                return View(addInfo);
            }
            SetAlertMsg("未知错误.");
            return View();
        }

        public ActionResult QuestionViewUc(int id)
        {
            var info = QuestionBLL.Get(id);
            if (info == null)
                return NotFound();
            return PartialView(info);
        }

    }
}
